package top.caoayu.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import top.caoayu.base.service.impl.DefaultPasswordUserDetailService;

@Configuration()
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public DefaultPasswordUserDetailService defaultPasswordUserDetailService() {
        return new DefaultPasswordUserDetailService();
    }
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        User.UserBuilder userBuilder = User.builder();
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        String encodePassword = passwordEncoder.encode("123456");
        inMemoryUserDetailsManager.createUser(userBuilder.username("admin").password(encodePassword).roles("admin").build());
        inMemoryUserDetailsManager.createUser(userBuilder.username("user").password(encodePassword).roles("user").build());
        return inMemoryUserDetailsManager;
    }
    @Bean
    public DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider(userDetailsService(passwordEncoder())));
        http.
                csrf().disable()
                .authorizeHttpRequests(custom -> custom.antMatchers("/login")
                        .permitAll()
                        .anyRequest()
                        .authenticated())
                .formLogin(v->v.loginPage("/login"))
                ;
        return http.build();
    }

}